package tyw.com.userms.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import tyw.com.userms.model.User;

public class DbManager {

    private DatabaseHelper helper;
    private SQLiteDatabase db;
    private Context context;

    public DbManager(Context context) {
        helper = new DatabaseHelper(context);
        db = helper.getWritableDatabase();
        this.context = context;
    }


    /**
     * 添加标签进数据库
     *
     * @param user
     */
    public void addUser(User user) {
        Cursor c = db.rawQuery("SELECT * FROM  users where name =?", new String[]{user.name});
        if (c.getCount() > 0) {
            c.close();
            return;
        }
        db.execSQL(" INSERT INTO users (name,phone) VALUES(?,?)", new String[]{user.name,user.phone});
        c.close();
    }


    /**
     * 获取所有的tagName
     *
     * @return
     */
    public List<User> getUserList() {

        Cursor c = db.rawQuery("SELECT * FROM  users  order BY Id desc",
                null);
        List<User> list = new ArrayList<>();

        while (c.moveToNext()) {


            String name = c.getString(c.getColumnIndex("name"));
            String phone = c.getString(c.getColumnIndex("phone"));
            User user = new User(name,phone);
            list.add(user);
        }
        c.close();
        return list;
    }


    public void deleteUser(User user){

        db.delete("users", "name=?", new String[]{user.name});

    }

}
